<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>10_使用$watch和$filter实现数据筛选</title>
    <script src="./lib/angularjs.js"></script>
</head>

<body ng-app="myApp" ng-controller="myCtrl">
    <label for="search">搜索：<input type="text" ng-model="searchVal" id="search"></label>
    <table border="1px" width="500px">
        <tr class="bold">
            <td ng-click="sorted('id')">编号 <span ng-if="!state.id">升序</span><span ng-if="state.id">降序</span></td>
            <td ng-click="sorted('goods')">商品 <span ng-if="!state.goods">升序</span><span ng-if="state.goods">降序</span>
            </td>
            <td ng-click="sorted('trade')">购买数 <span ng-if="!state.trade">升序</span><span ng-if="state.trade">降序</span>
            </td>
        </tr>
        <tr ng-repeat="(k, v) in temporaryData">
            <td>{{v.id}}</td>
            <td>{{v.goods}}</td>
            <td>{{v.trade}}</td>
        </tr>
    </table>
</body>
<script>
    const myApp = angular.module("myApp", [])
    myApp.controller("myCtrl", ["$scope", "$filter", function ($scope, $filter) {
        // 假设data是请求api后返回的数据
        $scope.data = [{ id: 1, goods: "车灯", trade: 33 }, { id: 2, goods: "车门", trade: 44 }, { id: 3, goods: "车镜", trade: 55 }, { id: 4, goods: "大门", trade: 38 }]

        // 用来装载api数据的临时数据变量
        $scope.temporaryData = $scope.data
        $scope.searchVal = ""
        $scope.$watch("searchVal", function (n, o) {
            console.log(n);
            $scope.temporaryData = $filter("filter")($scope.data, n)
        })
    }])
</script>

</html>